package com.dianpingmedia.common.utils;


import com.google.gson.Gson;
import org.apache.http.Header;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.util.Map;

//import static net.logstash.logback.marker.Markers.append;


/**
 * Created by Karl He on 2017-05-31.
 */
@Component
public class HttpRequest {

    public static Gson gson = new Gson();

    /**
     * 直接创建HttpClient连接
     * @param url 完整路径
     * @param map 内容Map
     * @return
     */
    public static String doPost(String url, Map map){

        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        return doPost(httpclient, url, map);
    }

    public static String doPost(String url, String json){

        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        return doPost(httpclient, url, json);
    }

    public static String doPost(CloseableHttpClient httpclient, String reqUrl, Map map)
    {
        return doPost(httpclient,reqUrl,gson.toJson(map));
    }

    public static String doPost(CloseableHttpClient httpclient, String reqUrl, String json)
    {
        String result = null;
        try {
            StringEntity entity = new StringEntity(json, Charset.forName("utf-8"));
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");//发送json数据需要设置contentType
            HttpPost httpPost = new HttpPost(reqUrl);
            httpPost.setEntity(entity);
            CloseableHttpResponse response = httpclient.execute(httpPost);
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)//SC_OK = 200
            {
                try {
                    result = EntityUtils.toString(response.getEntity());// 返回json格式
                }
                finally {
                    response.close();
                }
            }
            else if(response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) //302
            {
                String locationUrl = null;
                try {
                    Header header = response.getFirstHeader("location"); // 跳转的目标地址是在 HTTP-HEAD 中的
                    if(header != null)
                        locationUrl = header.getValue(); // 这就是跳转后的地址，再向这个地址发出新申请，以便得到跳转后的信息是啥。

                }
                finally {
                    response.close();
                }

                if(locationUrl != null)
                {
                    httpPost.abort();//释放请求
                    return doPost(locationUrl,json);
                }
            }

        }  catch (ClientProtocolException e)
        {

        }catch (Exception e) {//failed: Connection refused: connect

        }

        return result;
    }

    public static String doGet(String reqUrl)
    {
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        String result = null;
        HttpGet httpGet = null;
        try {
            httpGet = new HttpGet(reqUrl);
            CloseableHttpResponse response = httpclient.execute(httpGet);
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ //SC_OK = 200
                try {
                    result = EntityUtils.toString(response.getEntity());// 返回json格式
                }
                finally {
                    response.close();
                }
            }

        }  catch (ClientProtocolException e)
        {
//            if(PlanController.logger.isWarnEnabled())
//                PlanController.logger.warn(append("methodName","HttpRequest.doGet"),e.getMessage());
        }catch (Exception e) {
//            if(PlanController.logger.isWarnEnabled())
//                PlanController.logger.warn(append("methodName","HttpRequest.doGet"),e.getMessage());
        }
        finally {
            if(httpGet!=null) {
                httpGet.abort();
                httpGet = null;
            }
        }

        return result;
    }
}
